<?php

namespace app\controller\api;

use app\core\ApiController;
use app\service\BlessingOrderService;
use app\service\OrderService;
use think\facade\Log;
use app\core\Aop\AopClient;
use app\core\Aop\request\AlipayTradeAppPayRequest;

class Notify extends ApiController
{
    public function testadcs()
    {
        $rs = BlessingOrderService::invoke()->payOrder('OD1716472973995510010', 1);
        $this->response->success([]);
    }

    //支付通知
    public function notice()
    {
        if (!$xml = file_get_contents('php://input')) {
            $this->response->error('Not found data');
        }
        //将服务器返回的XML数据转化为数组
        $data = $this->xmlToArray($xml);
        //记录日志
        Log::write("回调通知内容: " . $xml);
        //订单信息
        $apikey = $this->app->config->get('app.app_key');//api-v3的密钥
        //保存微信服务器返回的签名sign
        $dataSign = $data['sign'];
        //sign不参与签名算法
        unset($data['sign']);
        // 生成签名
        $sign = $this->makeSign($data, $apikey);
        // 判断签名是否正确 判断支付状态
        if (($sign !== $dataSign) || ($data['return_code'] !== 'SUCCESS') || ($data['result_code'] !== 'SUCCESS')) {
            $this->response->error('签名失败');
        }
        $attach = json_decode($data['attach'], true);
        if ($attach['order_type'] != 1 && $attach['order_type'] != 2 && $attach['order_type'] != 3 && $attach['order_type'] != 4) {
            $this->response->error('订单类型错误');
        }
        $rs = BlessingOrderService::invoke()->payOrder($data['out_trade_no'], $attach['order_type']);
        if ($rs !== true) {
            $this->response->error('更新订单失败');
        }
        $this->response->success([]);
    }

    //xml 转换成数组
    private function xmlToArray($xml)
    {
        //禁止引用外部 xml 实体
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring), true);
        return $val;
    }

    private function makeSign($values, $apikey)
    {
        //签名步骤一：按字典序排序参数
        ksort($values);
        $string = $this->toUrlParams($values);
        //签名步骤二：在string后加入KEY
        $string = $string . '&key=' . $apikey;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 格式化参数格式化成url参数
     * @param $values
     * @return string
     */
    private function toUrlParams($values)
    {
        $buff = '';
        foreach ($values as $k => $v) {
            if ($k != 'sign' && $v != '' && !is_array($v)) {
                $buff .= $k . '=' . $v . '&';
            }
        }
        return trim($buff, '&');
    }

    public function test()
    {
        $url = 'http://device.api.fjxmlz.com:18081/api/bless?sn=0123456789ABCDE';
        $params = [
            'name' => '张三/李四',
            'bless' => '学业有成/身体健康',
            'type' => 1,
            'sn' => '0123456789ABCDE',
            'validTime' => '',
            'validType' => 'day',
            'validCount' => 30,
        ];
        $header = [
            'Content-Type: application/json'
        ];
        $params = json_encode($params);
        $result = $this->request_post($url, $header, $params);
        $result = json_decode($result, true);

        var_dump($result);
        exit();
    }

    public function request_post($url = '', $header = array(), $data_string = '')
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string))
            );
        }
        $result = curl_exec($ch);
        return $result;
    }

    public function aliNotice()
    {
        $aop = new AopClient;
        $aop->alipayrsaPublicKey = $this->app->config->get('app.alipay_rsa_public_key');
        Log::write("alipay.回调通知内容: " . json_encode($_POST));
        $maps = $_POST;
        $flag = $aop->rsaCheckV1($maps, NULL, "RSA2");
        // 判断签名是否正确 判断支付状态
        if ($flag !== true) {
            $this->response->error('签名失败');
        }
        if ($maps['trade_status'] != 'TRADE_SUCCESS') {
            $this->response->error('订单错误');
        }
        $rs = OrderService::invoke()->payOrder($maps['out_trade_no'], json_encode($maps));
        if ($rs !== true) {
            $this->response->error('更新订单失败');
        }
        $this->response->success([]);
    }
}